#!/usr/bin/env python
import os
import sys

from urllib.request import urlopen



# -*- coding:utf-8 -*-
# 网易云音乐，通过歌手id生成词云
import requests
import sys,re,os
# from wordcloud import WordCloud
# import matplotlib.pyplot as plt
# import jieba

from PIL import Image
import numpy as np
from lxml import etree

# headers = {
#     'Referer' :'网易云音乐',
#     'Host' : '网易云音乐',
#     'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
#     'User-Agent' : 'Chrome/10'
# }
#
# #获取歌词
# def get_song_lyric(headers, lyric_url):
#     res = requests.request('GET', lyric_url,headers=headers)
#     if 'lrc' in res.json():
#         lyric = res.json()['lrc']['lyric']
#         new_lyric = re.sub(r'[\d:.[\]]','',lyric)
#         return new_lyric
#     else:
#         return ''
#         print(res.json())
#
# #去除停用词
# def remove_stop_words(f):
#     stop_words = ['作词','作曲', '编曲', 'Arranger', '录音', '混音', '人声', 'Vocal', '弦乐', 'Keyboard', '键盘', '编辑', '助理', 'Assistants', 'Mixing', 'Editing', 'Recording', '音乐', '制作', 'Producer', '发行', 'produced', 'and', 'distributed']
#     for stop_word in stop_words:
#         f = f.replace(stop_word, '')
#     return f
#
# #生成词云
# def create_word_cloud(f):
#     print('根据词频，开始生成词云!')
#     f = remove_stop_words(f)
#     cut_text = ' '.join(jieba.cut(f, cut_all=False, HMM=True))
#     wc = WordCloud(
#         font_path = './wc.ttf',
#         max_words = 100,
#         width = 2000,
#         height = 1200,
#         )
#     print(cut_text)
#     wordcloud = wc.generate(cut_text)
#     #写词云图片
#     wordcloud.to_file('wanglihong_wordcloud.jpg')
#     #显示词云文件
#     plt.imshow(wordcloud)
#     plt.axis('off')
#     plt.show()
#
# #得到王力宏页面热门前50的歌曲ID，歌曲名
# def get_songs(artist_id):
#     page_url = '网易云音乐' + artist_id
#     #获取HTML
#     res = requests.request('GET', page_url, headers=headers)
#     #用xpath解析前50首热门歌曲
#     html = etree.HTML(res.text)
#     href_xpath = "//*[@id='hotsong-list']//a/@href"
#     name_xpath = "//*[@id='hotsong-list']//a/text()"
#     hrefs = html.xpath(href_xpath)
#     names = html.xpath(name_xpath)
#     #设置热门歌曲ID，歌名
#     song_ids = []
#     song_names = []
#     for href, name in zip(hrefs, names):
#         song_ids.append(href[9:])
#         song_names.append(name)
#         print(href, ' ', name)
#     return song_ids, song_names
#
# #设置热门歌手ID
# artist_id = '5346'
# [song_ids, song_names] = get_songs(artist_id)
#
# #所有歌词
# all_word = ''
# #获取每首歌歌词
# for (song_id, song_name) in zip(song_ids, song_names):
#     lyric_url = 'http://music.163.com/api/song/lyric?os=pc&id=' + song_id + '&lv=-1&kv=-1&tv=-1'
#     lyric = get_song_lyric(headers, lyric_url)
#     all_word = all_word + ' ' + lyric
#     print(song_name)
#
# #根据词频生成词云
# create_word_cloud(all_word)


import requests
from bs4 import BeautifulSoup
import urllib.request

headers = {
    'Referer': 'http://music.163.com/',
    'Host': 'music.163.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
}

# 歌单的url地址
play_url = 'http://music.163.com/playlist?id=12827021640'
# http://music.163.com/playlist?id=12827021640

# 获取页面内容
s = requests.session()
response = s.get(play_url, headers=headers).content

# 使用bs4匹配出对应的歌曲名称和地址
s = BeautifulSoup(response, 'lxml')
main = s.find('ul', {'class': 'f-hide'})

lists = []
for music in main.find_all('a'):
    list = []
    # print('{} : {}'.format(music.text, music['href']))
    musicUrl = 'http://music.163.com/song/media/outer/url' + music['href'][5:] + '.mp3'
    musicName = music.text
    # 单首歌曲的名字和地址放在list列表中
    list.append(musicName)
    list.append(musicUrl)
    # 全部歌曲信息放在lists列表中
    lists.append(list)

print(lists)

# 下载列表中的全部歌曲，并以歌曲名命名下载后的文件，文件位置为当前文件夹
for i in lists:
    url = i[1]
    name = i[0]
    try:
        print('正在下载', name)
        urllib.request.urlretrieve(url, './%s.mp3' % name)
        print('下载成功')
    except:
        print('下载失败')

# if __name__ == '__main__':
#     #
#     # html = urlopen('http://jr.jd.com/')
#     # print(html.read())
#
#     # html = urlopen('http://127.0.0.1:8000/play/1.html/')
#     # print(html.read())
#
#     os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'music.settings')
#     try:
#         from django.core.management import execute_from_command_line
#     except ImportError as exc:
#         raise ImportError(
#             "Couldn't import Django. Are you sure it's installed and "
#             "available on your PYTHONPATH environment variable? Did you "
#             "forget to activate a virtual environment?"
#         ) from exc
#     execute_from_command_line(sys.argv)



